"""数据库工具函数
包含数据库初始化、迁移等工具
"""
from flask import Flask
from flask_migrate import Migrate
from .models import db
from .models.user import User
from .models.task import Task, TaskExecution
from .models.system import SystemLog
from .models.enums import TaskStatus, TaskType
from .models.script import ScriptFolder, UserScript
from config import get_config
from datetime import datetime
import os
import traceback
import logging
import json
from .log_utils import log_system_event

# 获取日志记录器
logger = logging.getLogger(__name__)


migrate = Migrate()


def init_db(app: Flask):
    """初始化数据库"""
    try:
        db.init_app(app)
        migrate.init_app(app, db)
        
        with app.app_context():
            # 创建所有表
            db.create_all()
            
            # 创建默认管理员账户
            create_admin_user()
            
            # 记录数据库初始化成功的系统事件
            log_system_event(
                "INFO",
                "database",
                "数据库初始化成功",
                {
                    "operation": "database_initialization",
                    "status": "success"
                }
            )
            logger.info("数据库初始化完成")
    except Exception as e:
        logger.error(f"数据库初始化失败: {str(e)}")
        
        # 记录详细的系统错误日志
        logger.error(f"数据库初始化失败详情: {type(e).__name__}: {str(e)}\n{traceback.format_exc()}")
        raise


def create_admin_user():
    """创建默认管理员账户"""
    try:
        config = get_config()
        
        # 检查管理员账户是否已存在
        admin = User.query.filter_by(username=config.ADMIN_USERNAME).first()
        if not admin:
            admin = User(
                username=config.ADMIN_USERNAME,
                email=config.ADMIN_EMAIL,
                is_admin=True,
                is_active=True,
                created_at=datetime.utcnow()
            )
            admin.set_password(config.ADMIN_PASSWORD)
            
            db.session.add(admin)
            db.session.commit()
            
            # 记录系统事件日志
            log_system_event(
                level='INFO',
                module='database',
                message='默认管理员账户已创建',
                details=json.dumps({
                    'username': config.ADMIN_USERNAME,
                    'email': config.ADMIN_EMAIL,
                    'user_id': admin.id
                }, ensure_ascii=False),
                action='CREATE_ADMIN_USER',
                resource_type='USER',
                resource_id=str(admin.id)
            )
            
            # 记录管理员账户创建成功的系统事件
            logger.info(f"管理员账户创建成功: {config.ADMIN_USERNAME} ({config.ADMIN_EMAIL})")
        else:
            logger.info(f"管理员账户已存在: {config.ADMIN_USERNAME}")
    except Exception as e:
        logger.error(f"创建默认管理员账户失败: {str(e)}")
        
        # 记录详细的系统错误日志
        logger.error(f"创建管理员账户失败详情: {type(e).__name__}: {str(e)}\n{traceback.format_exc()}")
        
        # 回滚数据库事务
        try:
            db.session.rollback()
        except Exception as rollback_error:
            logger.error(f"数据库回滚失败: {str(rollback_error)}")
        
        raise


def get_db_stats():
    """获取数据库统计信息"""
    return {
        'users_count': User.query.count(),
        'tasks_count': Task.query.count(),
        'executions_count': TaskExecution.query.count(),
        'active_tasks_count': Task.query.filter_by(is_enabled=True).count()
    }


def cleanup_old_logs(days=30):
    """清理旧日志记录"""
    try:
        from datetime import timedelta
        cutoff_date = datetime.utcnow() - timedelta(days=days)
        
        old_logs = SystemLog.query.filter(SystemLog.created_at < cutoff_date).all()
        for log in old_logs:
            db.session.delete(log)
        
        old_executions = TaskExecution.query.filter(TaskExecution.started_at < cutoff_date).all()
        for execution in old_executions:
            db.session.delete(execution)
        
        db.session.commit()
        
        deleted_count = len(old_logs) + len(old_executions)
        
        # 记录清理操作成功的系统事件
        logger.info(f"数据库日志清理成功: 删除了{len(old_logs)}条日志和{len(old_executions)}条执行记录，共{deleted_count}条记录（{days}天前）")
        
        logger.info(f"清理了 {deleted_count} 条旧记录（{days} 天前）")
        return deleted_count
    except Exception as e:
        logger.error(f"清理旧日志记录失败: {str(e)}")
        
        # 记录详细的系统错误日志
        logger.error(f"清理旧日志记录失败详情: {type(e).__name__}: {str(e)}\n{traceback.format_exc()}")
        
        # 回滚数据库事务
        try:
            db.session.rollback()
        except Exception as rollback_error:
            logger.error(f"数据库回滚失败: {str(rollback_error)}")
        
        raise